<?php
$carID = $_POST['carID'];
$a = array();
if($_FILES['carPIC']['name'] == ''){
    $a['code'] = -1;
    $a['msg'] = '所有项目均为必填项。';
}
/*print_r($_FILES['carPIC']['error']);*/
switch($_FILES['carPIC']['error']) {
    case 1:// 文件大小超出了服务器的空间大小
        $a['code'] = -1;
        $a['msg'] = '上传文件太大了。';
        break;
    case 2:// 要上传的文件大小超出浏览器限制
        $a['code'] = -1;
        $a['msg'] = '上传文件太大了。';
        break;
    case 3:// 文件仅部分被上传
        $a['code'] = -1;
        $a['msg'] = '文件上传不完整。';
        break;
    case 4:// 没有找到要上传的文件
        $a['code'] = -1;
        $a['msg'] = '没有文件上传。';
        break;
    case 5:// 服务器临时文件夹丢失
        $a['code'] = -1;
        $a['msg'] = '服务器临时文件夹丢失。';
        break;
    case 6:// 文件写入到临时文件夹出错
        $a['code'] = -1;
        $a['msg'] = '文件写入到临时文件夹出错。';
        break;
    default:
        $a['code'] = 0;
}
if($a['code'] == -1){
    echo json_encode($a);
    exit;
}
//程序如果能到这里，说明上传文件正常
//首先判断文件扩展名是否正确
$allowType = array('jpg','jpeg','png','gif');
$fileName = explode(".",$_FILES['carPIC']['name']);
$exd = strtolower(end($fileName)); //得到扩展名
if(!in_array($exd,$allowType)){
    $a['code'] = -1;
    $a['msg'] = "文件类型出错。只能上传以下文件：".implode("，",$allowType);
    echo json_encode($a);
    exit;
}
//其次，判断文件大小，不超过1MB
if($_FILES['carPIC']['size'] > 1048576){
    $a['code'] = -1;
    $a['msg'] = "文件尺寸不能超过1MB";
    echo json_encode($a);
    exit;
}
$newFileName = uniqid('',true).".$exd";
if(move_uploaded_file($_FILES['carPIC']['tmp_name'],'./img/'.$newFileName)){
    //说明文件上传成功
    //在carinfo中添加一条记录
    include "conn.php";
    //更新当前图片
    $sql = "update carinfo set carPIC = '$newFileName' where id = $carID";
    $result = mysqli_query($conn,$sql);
    if($result){
        $pic = "<img style='width:100%' src='img/$newFileName'>";
        $a['code'] = 200;
        $a['pic'] = $pic;
    }
    else{
        $a['code'] = -1;
        $a['msg'] = "更新图片失败";
    }
    echo json_encode($a);
}
else{
    $a['code'] = -1;
    $a['msg'] = "更新图片失败";
    echo json_encode($a);
}

